package com.xxx.video.main.utils;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

import com.xxx.video.commen.dbs.beans.UploadFileBean;
import com.xxx.video.commen.dbs.utils.DbUtils;
import com.xxx.video.commen.utils.L;
import com.xxx.video.commen.utils.ListUtils;
import com.xxx.video.main.beans.LocalMediaInfoBean;
import com.xxx.video.network.listeners.UploadFileListener;
import com.xxx.video.network.utils.NetWorkUtils;

import java.io.File;
import java.util.ArrayList;

/**
 *
 */
public class UploadWorker extends Worker {

    public UploadWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    @NonNull
    @Override
    public Result doWork() {
        checkFile();
        return Result.success();
    }

    private void checkFile() {
        ArrayList<LocalMediaInfoBean> fileList = FilePoolManager.getInstance().getFileList();
        if (ListUtils.isEmpty(fileList)) {
            FilePoolManager.getInstance().startGetFile(null);
        } else {
            LocalMediaInfoBean localMediaInfoBean = fileList.get(0);
            UploadFileBean uploadFileBean = DbUtils.getInstance().queryUploadFileByPath(localMediaInfoBean.path);
            if (uploadFileBean == null) {
                uploadFile(localMediaInfoBean.path);
            } else {
                if (uploadFileBean.isUpload) {
                    FilePoolManager.getInstance().getFileList().remove(0);
                    checkFile();
                } else {
                    uploadFile(localMediaInfoBean.path);
                }
            }
        }
    }

    private void uploadFile(String path) {
        File file = new File(path);
        NetWorkUtils.getInstance().uploadPhoto(file, new UploadFileListener() {
            @Override
            public void onProgress(int progress) {

            }

            @Override
            public void onSuccess(Object successOb, String result) {
                L.d("上传文件", path);
                DbUtils.getInstance().insertUploadFileByPath(path);
            }

            @Override
            public void onFailure(Object failureObj) {

            }
        });
    }
}
